<!-- 维修执行页面 -->
<template>
  <div class="repair-exec">
    <basic-container>
      <el-tabs type="border-card" v-model="tabsIndex" @tab-click="handleTabClick">
        <el-tab-pane label="维修执行" name="1" @click="click">
          <div class="history-record"><el-button type="primary" size="medium" @click="historyRecord">历史维修记录查询</el-button></div>
          <avue-form ref="badConfirmProperties" v-model="badCodeModel" :option="badCodeOption" @submit="submitEvent" @reset-change="handleEmpty">
            <template slot="productSn">
              <el-input placeholder="请输入产品序列号" v-model="badCodeModel.productSn" @keyup.enter.native="enterProductSequenceNumber(badCodeModel.productSn)" clearable>
              </el-input>
            </template>
            <template slot="repairRefuellingInfo">
              <div v-for="(item, index) of repairRefuellingList" style="display: flex" :key="index">
                <label class="repiar_location_class">维修位号:</label>
                <div style="display: flex">
                  <el-input placeholder="请输入维修位号" v-model="repairRefuellingList[index].locationCode" style="margin-bottom: 10px; width: 369px" clearable></el-input>
                  <i class="iconfont iconicon_roundclose" v-if="index + 1 !== repairRefuellingList.length" @click="handleIconDelete(index)" style="margin-left: 10px"></i>
                  <i class="iconfont iconicon_roundadd" v-else @click="handleIconAdd()" style="margin-left: 10px"></i>
                </div>
                <div style="display: flex">
                  <div style="width: 125px"><span style="float: right; color: #606266">是否换料:</span></div>
                  <el-switch
                    class="isReload"
                    v-model="repairRefuellingList[index].isReload"
                    active-text="是"
                    inactive-text="否"
                    @change="handleIsReload(repairRefuellingList[index].isReload, index, '')"
                  >
                  </el-switch>
                </div>
                <el-button
                  class="btn-replace"
                  size="mini"
                  type="primary"
                  v-if="repairRefuellingList[index].isReload"
                  @click="handleIsReload(repairRefuellingList[index].isReload, index, 'DETAIL')"
                >
                  替代料详情
                </el-button>
              </div>
            </template>
            <template slot="imgUpload">
              <el-dropdown>
                <el-button type="primary"><i class="el-icon-upload"></i>&nbsp;&nbsp;图片上传</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <div @click="handleNativeUpload('native')">本地上传</div>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <div @click="handlePictureUpload('picture')">拍照上传</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <template slot="viewImg">
              <avue-upload
                class="viewImg"
                :propsHttp="propsHttp"
                :on-remove="removeFile"
                accept=".png,.jpg"
                data-type="array"
                list-type="picture-card"
                v-model="imgs"
              ></avue-upload>
            </template>
            <template slot="repairWay">
              <div class="repairWay">
                <div class="repairWayContent">
                  <el-radio v-model="badCodeModel.repairOutResult" label="REPAIR_OUT" v-remove-aria-hidden>维修合格，出维修</el-radio>
                  <span class="station" :key="timer" v-if="badCodeModel.repairOutResult == 'REPAIR_OUT'">
                    <label><span>*</span>指定返回工站：</label>
                    <el-select v-model="badCodeModel.returnRouteId" placeholder="请选择" clearable>
                      <el-option v-for="item in stationList" :key="item.id" :label="item.routeName" :value="item.id"></el-option>
                    </el-select>
                  </span>
                </div>
                <el-radio style="padding: 10px" v-model="badCodeModel.repairOutResult" label="REPAIR_REPEAT" v-remove-aria-hidden>维修不合格，返回重修</el-radio>
                <el-radio style="padding: 10px" v-model="badCodeModel.repairOutResult" label="REPAIR_SCRAP" v-remove-aria-hidden>无法维修，报废</el-radio>
              </div>
            </template>
          </avue-form>
        </el-tab-pane>
        <el-tab-pane label="测试数据" name="2">
          <repairDetail v-if="tabsIndex === '2'" class="repair-detail" :rowData="badCodeModel" :isAuto="true" :activeName="activeName" :immediately="true"></repairDetail>
        </el-tab-pane>
      </el-tabs>
    </basic-container>

    <el-dialog
      custom-class="repairExecDialog"
      title="换料"
      width="60%"
      top="3vh"
      v-if="repairEndVisible"
      :visible.sync="repairEndVisible"
      :modal-append-to-body="false"
      :append-to-body="true"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="sail-header-dialog-content">
        <avue-form ref="repairEndProperties" v-model="repairEndForm" :option="repairEndOption" @submit="handleConfirm">
          <template slot="packNo">
            <el-input
              type="text"
              placeholder="请输入物料包装条码"
              v-model="repairEndForm.packNo"
              suffix-icon="iconfont iconicon_scan"
              @keydown.enter.native="handleSequenceNumber(repairEndForm.packNo)"
            >
            </el-input>
          </template>
          <template slot="oldSn">
            <el-input
              type="text"
              suffix-icon="iconfont iconicon_scan"
              placeholder="请输入旧子件序列号"
              v-model="repairEndForm.oldSn"
              @keydown.enter.native="handleSubSn(repairEndForm.oldSn, 'OLD')"
            >
            </el-input>
          </template>
          <template slot="newSn">
            <el-input
              type="text"
              suffix-icon="iconfont iconicon_scan"
              placeholder="请输入新子件序列号"
              v-model="repairEndForm.newSn"
              @keydown.enter.native="handleSubSn(repairEndForm.newSn, 'NEW')"
            ></el-input>
          </template>
        </avue-form>
        <!-- 换料物料列表 -->
        <h3>原材料换料</h3>
        <avue-crud ref="reloadCrud" v-model="reload.form" :option="reload.option" :data="reload.data" @row-del="handleReloadRowDel"></avue-crud>
        <h3>子件换料</h3>
        <avue-crud ref="sonMaterialCrud" v-model="sumMaterial.form" :option="sumMaterial.option" :data="sumMaterial.data" @row-del="handleSumMaterialDel"></avue-crud>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseDialog" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="handleSaveData">提 交</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="uploadType === 'picture' ? '拍照上传不良' : '本地照片上传'"
      width="33%"
      :visible.sync="pictureVisible"
      :modal-append-to-body="false"
      :append-to-body="true"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-if="uploadType === 'picture'">
        <div class="video-container">
          <div class="video-warpper">
            <video id="video" autoplay style="width: 640px; height: 360px"></video>
            <canvas id="canvas" class="canvas" width="640" height="360"></canvas>
          </div>
        </div>
        <div class="video-footer">
          <el-button id="capture" type="primary" size="small" @click="handleClickCapture()">拍照上传 </el-button>
        </div>
      </div>
      <div v-if="uploadType === 'native'" class="video-container">
        <el-upload
          ref="fileUpload"
          class="upload-demo"
          drag
          multiple
          action="/api/blade-resource/oss/endpoint/put-file-attach"
          accept=".png,.jpg"
          list-type="picture"
          :headers="headersObj"
          :on-success="pictureUploadSuccess"
          :before-upload="beforeUpload"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </div>
</template>

<script>
import repairDetail from '@/components/repair/detail.vue';
import { compressImg } from '@/util/compressImg';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

import { getSnDetail, getFailureType, flagScrap, repairExec, uploadFile, getWorkOrderRoute, getSequenceNumber, positionNo, getSn } from '@/api/repair/repairExecOperation';
import website from '@/config/website';
import { getToken } from '@/util/auth';
import { mapGetters } from 'vuex';

const validateLocationCode = (rule, value, callback) => {
  let reg = /[\u4e00-\u9fa5]/;
  if (reg.test(value)) {
    callback(new Error('位号不能输入中文!'));
  } else {
    callback();
  }
};
const validatorQuantity = (rule, value, callback) => {
  let reg = /^[1-9]\d*$/g;
  if (!reg.test(value)) {
    callback(new Error('物料维修用量不能小于等于0并且是整数！'));
  } else {
    callback();
  }
};
export default {
  name: 'Repairexec',
  components: {
    CommonModalTemplate,
    repairDetail
  },
  data() {
    return {
      propsHttp: {
        res: {
          url: 'url',
          name: 'name'
        }
      },
      pageCode: 'repairExecOperation',
      tabsIndex: '1',
      isAuto: false,
      activeName: 'second',
      repairEndType: '',
      rowData: {},
      visibile: false,
      pictureVisible: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      fileUploadBox: false,
      fileList: [],
      imgs: [],
      data: [],
      stationList: [],
      repairRefuellingIndex: 0,
      repairRefuellingList: [
        {
          locationCode: '',
          isReload: false,
          refuelingList: []
        }
      ],
      serviceCodeList: [],
      badCodeModel: {
        repairOutResult: 'REPAIR_OUT'
      },
      video: {},
      uploadType: '',
      repairEndForm: {},
      userObj: {},
      repairEndOption: {
        submitBtn: true,
        emptyBtn: false,
        submitText: '录入',
        menuPosition: 'left',
        labelWidth: 130,
        column: [
          {
            label: '换料类型',
            prop: 'refuelingType',
            type: 'select',
            span: 8,
            value: 'MATERIAL',
            dicData: [
              {
                label: '原材料',
                value: 'MATERIAL'
              },
              {
                label: '子件组装料',
                value: 'COMPONENT'
              }
            ],
            control: (val, form) => {
              if (val === 'MATERIAL') {
                return {
                  inputType: {
                    display: true
                  },
                  packNo: {
                    display: false
                  },
                  partNo: {
                    display: true
                  },
                  partName: {
                    display: true
                  },
                  partModel: {
                    display: true
                  },
                  partBrand: {
                    display: true
                  },
                  newPartNo: {
                    display: false
                  },
                  newPartName: {
                    display: false
                  },
                  newPartModel: {
                    display: false
                  },
                  newPartBrand: {
                    display: false
                  },
                  oldSn: {
                    display: false
                  },
                  newSn: {
                    display: false
                  },
                  productPartNo: {
                    display: false
                  },
                  productPartName: {
                    display: false
                  },
                  productPartModel: {
                    display: false
                  },
                  lotNo: {
                    display: false
                  },
                  newLotNo: {
                    display: false
                  }
                };
              } else if (val === 'COMPONENT') {
                return {
                  inputType: {
                    display: false
                  },
                  packNo: {
                    display: false
                  },
                  partNo: {
                    display: false
                  },
                  partName: {
                    display: false
                  },
                  partModel: {
                    display: false
                  },
                  partBrand: {
                    display: false
                  },
                  newPartNo: {
                    display: false
                  },
                  newPartName: {
                    display: false
                  },
                  newPartModel: {
                    display: false
                  },
                  newPartBrand: {
                    display: false
                  },
                  oldSn: {
                    display: true
                  },
                  newSn: {
                    display: true
                  },
                  productPartNo: {
                    display: true
                  },
                  productPartName: {
                    display: true
                  },
                  productPartModel: {
                    display: true
                  },
                  lotNo: {
                    display: false
                  },
                  newLotNo: {
                    display: false
                  }
                };
              }
            },
            rules: [
              {
                required: true,
                message: '请选择换料类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '旧子件序列号',
            prop: 'oldSn',
            span: 8,
            display: false
          },
          {
            label: '新子件序列号',
            prop: 'newSn',
            span: 8,
            display: false,
            rules: [
              {
                required: true,
                message: '请输入新子件序列号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            span: 8,
            disabled: true,
            display: false
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            span: 8,
            disabled: true,
            display: false
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            span: 8,
            disabled: true,
            display: false
          },
          {
            label: '录入类型',
            prop: 'inputType',
            type: 'select',
            span: 8,
            value: 'NONE_PACKING_SN',
            dicData: [
              {
                label: '无条码',
                value: 'NONE_PACKING_SN'
              },
              {
                label: '有条码',
                value: 'HAVE_PACKING_SN'
              }
            ],
            control: (val, form) => {
              if (val === 'HAVE_PACKING_SN' && form.refuelingType === 'MATERIAL') {
                return {
                  packNo: {
                    display: true
                  },
                  partNo: {
                    display: false
                  },
                  partName: {
                    display: false
                  },
                  partModel: {
                    display: false
                  },
                  partBrand: {
                    display: false
                  },
                  newPartNo: {
                    display: true
                  },
                  newPartName: {
                    display: true
                  },
                  newPartModel: {
                    display: true
                  },
                  newPartBrand: {
                    display: true
                  },
                  lotNo: {
                    display: false
                  },
                  newLotNo: {
                    display: true
                  }
                };
              } else if (val === 'NONE_PACKING_SN' && form.refuelingType === 'MATERIAL') {
                return {
                  packNo: {
                    display: false
                  },
                  partNo: {
                    display: true
                  },
                  partName: {
                    display: true
                  },
                  partModel: {
                    display: true
                  },
                  partBrand: {
                    display: true
                  },
                  newPartNo: {
                    display: false
                  },
                  newPartName: {
                    display: false
                  },
                  newPartModel: {
                    display: false
                  },
                  newPartBrand: {
                    display: false
                  },
                  lotNo: {
                    display: true
                  },
                  newLotNo: {
                    display: false
                  }
                };
              }
            }
          },
          {
            label: '物料编码',
            prop: 'partNo',
            span: 8,
            type: 'search',
            display: true,
            disabled: true,
            appendClick: () => {
              this.openPartModal();
            },
            rules: [
              {
                required: true,
                message: '请选择物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料包装条码',
            prop: 'packNo',
            span: 8,
            display: false,
            rules: [
              {
                required: true,
                message: '请扫描物料包装条码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料名称',
            prop: 'partName',
            span: 8,
            disabled: true,
            display: true
          },
          {
            label: '物料名称',
            prop: 'newPartName',
            span: 8,
            disabled: true,
            display: true
          },
          {
            label: '物料编码',
            prop: 'newPartNo',
            span: 8,
            disabled: true,
            display: false
          },
          {
            label: '物料型号',
            prop: 'partModel',
            span: 8,
            disabled: true
          },
          {
            label: '物料型号',
            prop: 'newPartModel',
            span: 8,
            disabled: true,
            display: false
          },
          {
            label: '物料品牌',
            prop: 'partBrand',
            display: true,
            span: 8,
            rules: [
              {
                required: true,
                message: '请选择物料品牌',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料品牌',
            prop: 'newPartBrand',
            span: 8,
            disabled: true,
            display: false
          },
          {
            label: '内部批次',
            prop: 'lotNo',
            span: 8,
            display: true,
            rules: [
              {
                required: true,
                message: '请选择内部批次',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '内部批次',
            prop: 'newLotNo',
            span: 8,
            display: false,
            disabled: true
          },
          {
            label: '维修用量',
            prop: 'quantity',
            span: 8,
            type: 'number',
            rules: [
              {
                required: true,
                message: '请输入维修用量',
                trigger: 'blur'
              },
              {
                required: true,
                trigger: 'blur',
                validator: validatorQuantity
              }
            ]
          }
        ]
      },
      badCodeOption: {
        submitBtn: true,
        emptyBtn: true,
        menuPosition: 'right',
        group: [
          {
            label: '基础信息',
            arrow: false,
            prop: 'baseInfo',
            icon: 'el-icon-vertical-bar',
            labelWidth: 150,
            column: [
              {
                label: '序列号',
                prop: 'productSn',
                span: 6,
                minWidth: 100,
                rules: [
                  {
                    required: true,
                    message: '请输入产品序列号',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '产品编码',
                prop: 'productPartNo',
                span: 6,
                search: true,
                disabled: true
              },
              {
                label: '产品名称',
                prop: 'productPartName',
                span: 6,
                search: true,
                disabled: true
              },
              {
                label: '产品型号',
                prop: 'productPartModel',
                span: 6,
                search: true,
                disabled: true
              },
              {
                label: '工单号',
                prop: 'workOrderNo',
                span: 6,
                disabled: true
              },

              {
                label: '工单计划数量',
                prop: 'workOrderPlanQuantity',
                span: 6,
                disabled: true
              },
              {
                label: '工单完工数量',
                prop: 'workOrderCompletedQuantity',
                span: 6,
                disabled: true
              },
              {
                label: '工单不良数',
                prop: 'workOrderNgQuantity',
                span: 6,
                disabled: true
              },
              {
                label: '已维修次数',
                prop: 'repairTimes',
                span: 6,
                disabled: true
              }
            ]
          },
          {
            label: '不良信息',
            arrow: false,
            prop: 'failureInfo',
            icon: 'el-icon-vertical-bar',
            labelWidth: 150,
            column: [
              {
                label: '不良现象',
                prop: 'badPhenomenonName',
                disabled: true,
                span: 6
              },
              {
                label: '登记产线',
                prop: 'lineName',
                disabled: true,
                span: 6
              },
              {
                label: '登记工序',
                prop: 'routeName',
                disabled: true,
                span: 6
              },
              {
                label: '登记工位',
                prop: 'stationName',
                disabled: true,
                span: 6
              },
              {
                label: '登记人员',
                prop: 'registerUserName',
                disabled: true,
                span: 6
              },
              {
                label: '登记时间',
                prop: 'registerTime',
                disabled: true,
                span: 6
              },
              {
                label: '判定人员',
                prop: 'confirmUserName',
                span: 6,
                disabled: true
              },
              {
                label: '判定时间·',
                prop: 'confirmTime',
                span: 6,
                disabled: true
              },
              {
                label: '登记说明',
                prop: 'registerDescription',
                disabled: true,
                type: 'textarea',
                row: true,
                minRows: 3,
                maxRows: 3,
                span: 6
              },
              {
                label: '判定说明',
                prop: 'confirmDescription',
                disabled: true,
                type: 'textarea',
                minRows: 3,
                maxRows: 3,
                span: 12
              }
            ]
          },
          {
            label: '维修信息',
            arrow: false,
            prop: 'repairInfo',
            icon: 'el-icon-vertical-bar',
            labelWidth: 150,
            column: [
              {
                label: '不良原因大类',
                prop: 'mainCauseName',
                type: 'select',
                span: 6,
                dicUrl: '/api/mes-product/mro-dict/list?dictType=BAD_CAUSE',
                props: {
                  label: 'name',
                  value: 'id'
                },
                dicFormatter: (data) => {
                  return data.data;
                },
                cascader: ['subCauseName'],
                rules: [
                  {
                    required: true,
                    message: '请选择不良原因大类',
                    trigger: 'change'
                  }
                ]
              },
              {
                label: '不良原因小类',
                prop: 'subCauseName',
                type: 'select',
                dicFlag: false,
                span: 6,
                dicUrl: '/api/mes-product/mro-dict/detail?id={{key}}',
                props: {
                  label: 'name',
                  value: 'id'
                },
                dicFormatter: (data) => {
                  return data.data.subList;
                },
                rules: [
                  {
                    required: true,
                    message: '请选择不良原因小类',
                    trigger: 'change'
                  }
                ]
              },
              {
                label: '原因说明',
                prop: 'badCauseDescription',
                type: 'textarea',
                row: true,
                minRows: 3,
                maxRows: 3,
                span: 12
              },
              {
                label: '维修结果',
                prop: 'repairResult',
                type: 'select',
                span: 6,
                dicData: [
                  {
                    label: '维修完成',
                    value: 'REPAIR_FINISHED'
                  },
                  {
                    label: '标记报废',
                    value: 'MARK_SCRAP'
                  }
                ],
                change: ({ value }) => {
                  if (value === 'REPAIR_FINISHED') {
                  }
                },
                control: (val, form) => {
                  if (val === 'REPAIR_FINISHED') {
                    return {
                      repairRefuellingInfo: {
                        display: true
                      },
                      imgUpload: {
                        display: true
                      },
                      repairRemark: {
                        display: true
                      },
                      scrapRemark: {
                        display: false
                      }
                    };
                  } else if (val === 'MARK_SCRAP') {
                    return {
                      repairRefuellingInfo: {
                        display: false
                      },
                      imgUpload: {
                        display: false
                      },
                      repairRemark: {
                        display: false
                      },
                      scrapRemark: {
                        display: true
                      }
                    };
                  }
                },
                rules: [
                  {
                    required: true,
                    message: '请选择维修结果',
                    trigger: 'change'
                  }
                ]
              },

              {
                label: '维修说明',
                prop: 'repairRemark',
                type: 'textarea',
                display: false,
                row: true,
                minRows: 3,
                maxRows: 3,
                span: 12
              },
              {
                label: '报废说明',
                prop: 'scrapRemark',
                type: 'textarea',
                row: true,
                display: false,
                minRows: 3,
                maxRows: 3,
                span: 12
              },
              {
                label: '', //维修位号信息
                labelWidth: 0,
                prop: 'repairRefuellingInfo',
                display: false,
                row: true,
                span: 24
              },
              {
                label: '维修图片',
                prop: 'imgUpload',
                display: false,
                row: true
              },
              {
                label: '',
                prop: 'viewImg',
                type: 'upload',
                dataType: 'string',
                listType: 'picture-card',
                row: true,
                span: 24
              }
            ]
          },
          {
            label: '出维修信息',
            prop: 'handleSuggest',
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '',
                prop: 'repairWay',
                width: 0,
                labelWidth: 16,
                span: 24
              },
              {
                label: '出维修意见说明',
                prop: 'repairOutDescription',
                type: 'textarea',
                span: 12,
                maxRows: 3,
                minRows: 3,
                labelWidth: 160
              }
            ]
          }
        ]
      },
      repairEndVisible: false,
      reload: {
        form: {},
        data: [],
        option: {
          columnBtn: false,
          refreshBtn: false,
          addBtn: false,
          editBtn: false,
          menu: true,
          labelWidth: 130,
          menuWidth: 100,
          maxHeight: 300,
          border: true,
          index: true,
          indexLabel: '序号',
          column: [
            {
              label: '序列号',
              prop: 'productSn',
              span: 24
            },
            {
              label: '维修位号',
              prop: 'locationCode',
              span: 24
            },
            {
              label: '录入类型',
              prop: 'inputType',
              type: 'select',
              dicData: [
                {
                  label: '无条码',
                  value: 'NONE_PACKING_SN'
                },
                {
                  label: '有条码',
                  value: 'HAVE_PACKING_SN'
                }
              ]
            },
            {
              label: '物料包装条码',
              prop: 'packNo'
            },
            {
              label: '物料编码',
              prop: 'partNo'
            },
            {
              label: '物料名称',
              prop: 'partName'
            },
            {
              label: '物料品牌',
              prop: 'partBrand'
            },
            {
              label: '内部批次',
              prop: 'lotNo'
            },
            {
              label: '维修用量',
              prop: 'quantity'
            }
          ]
        }
      },
      sumMaterial: {
        form: {},
        data: [],
        option: {
          columnBtn: false,
          refreshBtn: false,
          addBtn: false,
          editBtn: false,
          menu: true,
          labelWidth: 130,
          menuWidth: 100,
          maxHeight: 300,
          border: true,
          index: true,
          indexLabel: '序号',
          column: [
            {
              label: '维修位号',
              prop: 'locationCode',
              span: 24
            },
            {
              label: '旧子件序列号',
              prop: 'oldSn'
            },
            {
              label: '新子件序列号',
              prop: 'newSn'
            },
            {
              label: '产品编码',
              prop: 'productPartNo'
            },

            {
              label: '产品名称',
              prop: 'productPartName'
            },
            {
              label: '产品型号',
              prop: 'productPartModel'
            },
            {
              label: '维修用量',
              prop: 'quantity'
            }
          ]
        }
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.repairExec_view, false)
      };
    }
  },
  async mounted() {
    try {
      let query = this.$route.query || {};
      if (query.productSequenceNumber && query.productSequenceNumber !== 'undefined') {
        this.enterProductSequenceNumber(query.productSequenceNumber);
      } else {
        this.badCodeModel.productSn = '';
      }
    } catch (e) {
      console.log(e);
    }
  },
  watch: {
    'badCodeModel.repairOutResult'(val) {
      if (val !== 'REPAIR_OUT') {
        this.badCodeModel.returnRouteId = '';
      }
    }
  },
  created() {},
  methods: {
    historyRecord() {
      this.$router.replace({ path: '/report/maintenance-record-query', query: { productSn: this.badCodeModel.productSn } });
    },
    findWorkOrderRoute(workorderId) {
      getWorkOrderRoute({ workorderId }).then((res) => {
        let data = res.data.data || [];
        this.stationList = data;
      });
    },
    /**
     * 序列号回车
     * */
    enterProductSequenceNumber(productSn) {
      let params = {
        productSn
      };
      getSnDetail(params).then((res) => {
        let data = res.data.data || {};
        this.badCodeModel = data;
        this.$message.success(res.data.msg);
        this.findWorkOrderRoute(this.badCodeModel.workOrderId);
      });
    },
    handleIsReload(isReload, idx, type) {
      this.repairRefuellingIndex = idx;
      this.repairEndVisible = isReload;
      this.repairEndType = type;
      this.locationCode = this.repairRefuellingList[idx].locationCode;
      this.repairRefuellingList.forEach((item, index) => {
        if (index === idx) {
          this.reload.data = item.refuelingList.filter((el) => el.refuelingType === 'MATERIAL');
          this.sumMaterial.data = item.refuelingList.filter((el) => el.refuelingType !== 'MATERIAL');
        }
      });
    },
    handleIconAdd() {
      this.repairRefuellingList.push({
        id: this.repairRefuellingList.length + 1,
        locationCode: '',
        isReload: false,
        refuelingList: []
      });
    },
    handleIconDelete(idx) {
      this.repairRefuellingList.splice(idx, 1);
    },
    handleNativeUpload(type) {
      this.uploadType = type;
      this.pictureVisible = true;
    },
    handlePictureUpload(type) {
      this.uploadType = type;
      if (
        navigator.mediaDevices &&
        (navigator.mediaDevices.getUserMedia || navigator.mediaDevices.webkitGetUserMedia || navigator.mediaDevices.mozGetUserMedia || navigator.mediaDevices.getUserMedia)
      ) {
        this.getUserMediaToPhoto({ video: { width: 640, height: 360 } });
      } else {
        alert('不支持访问用户媒体设备');
      }
      this.pictureVisible = true;
    },
    /**
     *
     * 调用用户媒体设备
     */
    async getUserMediaToPhoto(constraints) {
      try {
        if (navigator.mediaDevices.getUserMedia) {
          console.log('0');
          const res = await navigator.mediaDevices.getUserMedia(constraints);
          res.active ? this.success(res) : this.error(res);
        } else if (navigator.mediaDevices.webkitGetUserMedia) {
          console.log('1');
          navigator.mediaDevices.webkitGetUserMedia(
            constraints,
            () => {
              this.success;
            },
            () => {
              this.error;
            }
          );
        } else if (navigator.mediaDevices.mozGetUserMedia) {
          console.log('2');
          navigator.mediaDevices.mozGetUserMedia(
            constraints,
            () => {
              this.success;
            },
            () => {
              this.error;
            }
          );
        } else if (navigator.mediaDevices.getUserMedia) {
          console.log('3');
          navigator.mediaDevices.getUserMedia(
            constraints,
            () => {
              this.success;
            },
            () => {
              this.error;
            }
          );
        }
      } catch (e) {
        alert('访问用户媒体设备不存在');
      }
    },
    /**
     * 成功回调函数
     * @param stream 视频流
     */
    success(stream) {
      var video = document.querySelector('#video');
      video.srcObject = stream;
      this.video = video;
      // onloadedmetadata 事件在指定视频/音频（audio/video）的元数据加载后触发。
      video.addEventListener('loadedmetadata', () => {
        video.play();
        this.clearCanvas(video);
      });
    },
    /**
     * 清空画布
     */
    clearCanvas(video) {
      // 16ms 调用回话绘画一次，以免实时保持画布准确
      if (document.getElementById('canvas')) {
        window.requestAnimationFrame(() => {
          this.clearCanvas(video);
        });
        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      }
    },

    /**
     * 拍照按钮点击事件
     */
    handleClickCapture() {
      let canvas = document.getElementById('canvas');
      let ctx = canvas.getContext('2d');
      // TODO: 测试图片清晰 细化画布分辨率？？？ 暂未实现
      // ctx.translate(0.5, 0.5);
      let imgData = canvas.toDataURL('image/png');
      ctx.drawImage(this.video, 0, 0, canvas.width, canvas.height);
      let imgFile = this.base64ToFile(imgData, this.guid());
      let formData = new FormData();
      formData.append('file', imgFile);
      uploadFile(formData).then((res) => {
        let data = res.data.data || {};
        data.attachmentName = data.originalName || '';
        this.fileList.push(data);
        this.imgs.push(data.link);
        this.$message.success('操作成功');
      });
    },
    guid() {
      return 'xxxxxxxx4xxxyxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },

    base64ToFile(code, fileName) {
      const parts = code.split(';base64,');
      const contentType = parts[0].split(':')[1];
      const fileExt = contentType.split('/')[1];
      const raw = window.atob(parts[1]);
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new File([uInt8Array], `${fileName}.${fileExt}`, {
        type: contentType
      });
    },
    handleSubSn(sn, type) {
      getSn({
        sequenceNumber: sn
      }).then((res) => {
        this.$message({
          type: 'success',
          message: res.data.msg
        });
        let data = res.data.data || {};
        if (type === 'NEW') {
          this.$set(this.repairEndForm, 'productPartName', data.productPartName);
          this.$set(this.repairEndForm, 'productPartNo', data.productPartNo);
          this.$set(this.repairEndForm, 'productPartModel', data.productPartModel);
          this.repairEndForm.lotNo = data.lotNo;
          this.repairEndForm.productPartBrand = data.partBrand;
        } else {
          this.$set(this.repairEndForm, 'partName', data.productPartName);
          this.$set(this.repairEndForm, 'partNo', data.productPartNo);
          this.$set(this.repairEndForm, 'partModel', data.productPartModel);
        }
      });
    },
    //物料包装条码
    handleSequenceNumber(packNo) {
      getSequenceNumber({
        sequenceNumber: packNo
      })
        .then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          let data = res.data.data || {};
          this.$set(this.repairEndForm, 'newPartNo', data.partNo);
          this.$set(this.repairEndForm, 'newPartName', data.partName);
          this.$set(this.repairEndForm, 'newPartModel', data.partModel);
          this.$set(this.repairEndForm, 'newPartBrand', data.partBrand);
          this.$set(this.repairEndForm, 'newLotNo', data.lotNo);

          this.$set(this.repairEndForm, 'partNo', data.partNo);
          this.$set(this.repairEndForm, 'partName', data.partName);
          this.$set(this.repairEndForm, 'partModel', data.partModel);
          this.$set(this.repairEndForm, 'partBrand', data.partBrand);
          this.$set(this.repairEndForm, 'lotNo', data.lotNo);
        })
        .catch((err) => {
          this.repairEndForm.packNo = '';
        });
    },
    handleConfirm() {
      this.$refs.repairEndProperties.validate((valid, done) => {
        if (valid) {
          this.repairEndForm.locationCode = this.locationCode;
          if (this.repairEndForm.refuelingType === 'MATERIAL') {
            this.repairEndForm.productSn = this.badCodeModel.productSn;
            if (this.repairEndForm.inputType === 'HAVE_PACKING_SN') {
              this.repairEndForm.lotNo = this.repairEndForm.newLotNo;
              let haveCodeFlag = this.reload.data.some((item) => item.packNo === this.repairEndForm.packNo);
              if (haveCodeFlag) {
                this.$message({
                  type: 'warning',
                  message: '物料包装条码已存在，请重新录入！'
                });
                done();
                return;
              }
              this.reload.data.push(this._cloneDeep(this.repairEndForm));
            } else {
              let noCodeFlag = this.reload.data.some((item) => item.partNo === this.repairEndForm.partNo);
              if (noCodeFlag) {
                this.$message({
                  type: 'warning',
                  message: '物料编码已存在，请重新录入！'
                });
                done();
                return;
              }
              this.reload.data.push(this._cloneDeep(this.repairEndForm));
            }
          } else if (this.repairEndForm.refuelingType === 'COMPONENT') {
            let newSnFlag = this.sumMaterial.data.some((item) => item.newSn === this.repairEndForm.newSn);
            if (newSnFlag) {
              this.$message({
                type: 'warning',
                message: '新子件序列号已存在，请重新录入！'
              });
              done();
              return;
            }
            this.sumMaterial.data.push(this._cloneDeep(this.repairEndForm));
          }
        }
        let refuelingType = this.repairEndForm.refuelingType;
        let inputType = this.repairEndForm.inputType;
        this.$refs.repairEndProperties.resetFields();
        this.repairEndForm.inputType = inputType;
        this.repairEndForm.refuelingType = refuelingType;
        done();
      });
    },
    handleEmpty() {
      this.reload.data = [];
      this.sumMaterial.data = [];
      this.fileList = [];
      this.imgs = [];
      this.stationList = [];
      this.repairRefuellingList = [
        {
          locationCode: '',
          isReload: false,
          refuelingList: []
        }
      ];
      this.badCodeModel.repairOutResult = '';
      this.$refs.badConfirmProperties.resetFields();
      this.badCodeModel.repairOutResult = 'REPAIR_OUT';
      this.badCodeModel.returnRouteId = '';
      this.badCodeModel = {};
      this.newKey();
    },
    submitEvent() {
      this.$refs.badConfirmProperties.validate((valid, done) => {
        if (valid) {
          let locationList = this.repairRefuellingList.map((item) => {
            let refuelingList = item.refuelingList.map((item) => {
              if (item.refuelingType === 'MATERIAL') {
                item.newSn = item.packNo;
                item.newPartNo = item.inputType === 'NONE_PACKING_SN' ? item.partNo : item.newPartNo;
                item.newPartName = item.inputType === 'NONE_PACKING_SN' ? item.partName : item.newPartName;
                item.newPartModel = item.inputType === 'NONE_PACKING_SN' ? item.partModel : item.newPartModel;
                item.newPartBrand = item.inputType === 'NONE_PACKING_SN' ? item.partBrand : item.newPartBrand;
                item.newLotNo = item.inputType === 'NONE_PACKING_SN' ? item.lotNo : item.newLotNo;
              } else if (item.refuelingType === 'COMPONENT') {
                item.oldPartNo = item.partNo;
                item.oldPartName = item.partName;
                item.oldPartModel = item.partModel;
                item.oldPartBrand = item.partBrand;
                item.oldLotNo = item.lotNo;
                item.newPartNo = item.productPartNo;
                item.newPartName = item.productPartName;
                item.newPartModel = item.productPartModel;
                item.newPartBrand = item.productPartBrand;
              }
              delete item.lotNo;
              delete item.packNo;
              delete item.partName;
              delete item.partModel;
              delete item.partBrand;
              return item;
            });
            return {
              locationCode: item.locationCode,
              isRefueling: item.isReload,
              refuelingList
            };
          });
          done();
          if (this.badCodeModel.repairOutResult == 'REPAIR_OUT' && !this.badCodeModel.returnRouteId) {
            this.$message.warning('请选择指定返回工站！');
            return;
          }
          let params = {
            repairConfirmId: this.badCodeModel.repairConfirmId,
            mainBadCauseId: this.badCodeModel.mainCauseName,
            subBadCauseId: this.badCodeModel.subCauseName,
            badCauseDescription: this.badCodeModel.badCauseDescription,
            repairResult: this.badCodeModel.repairResult,
            repairDescription: this.badCodeModel.repairResult === 'REPAIR_FINISHED' ? this.badCodeModel.repairRemark : this.badCodeModel.scrapRemark,
            repairOutResult: this.badCodeModel.repairOutResult,
            returnRouteId: this.badCodeModel.returnRouteId,
            repairOutDescription: this.badCodeModel.repairOutDescription,
            locationList,
            attachmentList: this.fileList
          };
          console.log(params, 'params');
          repairExec(params)
            .then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功！'
              });
            })
            .then(() => {
              this.handleEmpty();
            });
        }
        done();
      });
    },
    findNode(list = [], prop) {
      let node;
      list.forEach((ele) => {
        if (ele.prop === prop) node = ele;
      });
      return node;
    },
    handleTabClick() {},
    removeFile(file) {
      this._forEach(this.fileList, (item, index) => {
        if (item.link === file.url) {
          this.fileList.splice(index, 1);
        }
      });
      this._forEach(this.imgs, (value, index) => {
        if (value === file.url) {
          this.imgs.splice(index, 1);
        }
      });
    },
    pictureUploadSuccess(res) {
      this.fileList.push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        attachmentName: res.data.originalName
      });
      this.imgs.push(res.data.link);
      this.$message.success('操作成功');
    },
    beforeUpload(file) {
      return new Promise(async (resolve, reject) => {
        if (!file.type.includes('image')) {
          this.$message.warning('请上传图片');
          reject(new Error('请上传图片'));
          return;
        }
        if (file.type != 'image/png' && file.type != 'image/jpeg') {
          this.$message.warning('请上传正确的文件类型！');
          reject(new Error('请上传正确的文件类型！'));
          return;
        }
        try {
          const newFile = await compressImg(file);
          resolve(newFile);
        } catch (e) {
          console.log(e);
        }
      });
    },
    // // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'repairCode':
          this.serviceCodeList = rowData;
          this.badCodeModel.repairCode = String(this._map(this.serviceCodeList, (item) => item.code));
          break;
        case 'vendorModal':
          this.repairEndForm.newVendorCode = this._get(rowData, 'partnerNo', '');
          break;
        case 'principalModal':
          this.badCodeModel.operator = this._get(rowData, 'id', '');
          this.badCodeModel.operatorName = this._get(rowData, 'name', '');
          break;
        case 'partModal':
          this.repairEndForm.partNo = this._get(rowData, 'partNo', '');
          this.repairEndForm.partName = this._get(rowData, 'partName', '');
          this.repairEndForm.partModel = this._get(rowData, 'partModel', '');
          this.repairEndForm.partMasterId = this._get(rowData, 'partMasterId', '');
          break;
        default:
          break;
      }
    },
    handleReloadRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reload.data.splice(index, 1);
          this.repairRefuellingList[this.repairRefuellingIndex].refuelingList = this.reload.data;
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleSumMaterialDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.sumMaterial.data.splice(index, 1);
          this.repairRefuellingList[this.repairRefuellingIndex].refuelingList = this.sumMaterial.data;
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    openPartModal() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料（双击进行选择）',
        url: `/api/mes-admin/bom/detail/list-by-partNo-and-positionNo?productPartNo=${this.badCodeModel.productPartNo}&locationCode=${this.locationCode}`,
        isPage: false,
        noPageParams: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'partName',
            search: true
          }
        ]
      };
    },
    openRepairCodeModel() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'repairCode';
      this.tableOption = {
        modalTitle: '选择维修代码信息（双击进行选择）',
        url: '/api/mes-product/mro/dict/list?dictType=ACTION',
        isPage: true,
        index: false,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          }
        ]
      };
    },
    /**
     * 打开供应商选择模态框
     */
    openVendorCommonModal() {
      this.modalName = 'vendorModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/partner/page?partnerType=SUPPLIER',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 130,
        columnDefs: [
          {
            label: '供应商编码',
            prop: 'partnerNo',
            search: true
          },
          {
            label: '供应商名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    /**
     * 打开用户选择模态框
     */
    openUserCommonModal() {
      this.modalName = 'principalModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择维修员（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    handleCloseDialog() {
      this.reload.data = [];
      this.sumMaterial.data = [];
      this.repairEndVisible = false;
      this.repairRefuellingList[this.repairRefuellingIndex].isReload = false;
    },
    handleSaveData() {
      this.repairRefuellingList[this.repairRefuellingIndex].refuelingList = [...this.reload.data, ...this.sumMaterial.data];
      this.repairEndVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.repairExecDialog {
  .centerForm1 {
    ::v-deep .el-form-item__label {
      line-height: 40px !important;
    }

    .inline {
      width: 50%;
      display: inline-block;

      &.repairId {
        .el-select {
          width: 80%;
        }
      }
    }
  }
}

.box-card {
  height: 120px;
  width: 174px;
  position: absolute;
  right: 21px;
  top: 65px;

  .card-list {
    position: relative;
    display: flex;
    align-items: center;
    flex-direction: column;
    margin-top: 21px;
    margin-left: -20px;

    li {
      font-size: 14px;
      height: 20px;
    }
  }
}

::v-deep .repair-detail .el-tabs__header {
  display: none;
}

::v-deep .custom-title {
  font-size: 16px;
}

.mark-btn {
  display: flex;
  justify-content: flex-end;
}

::v-deep .repair-select-row {
  background: #caf982 !important;
}

::v-deep .el-tabs {
  height: 83vh;
  overflow-y: scroll;
}

.repair {
  position: relative;
}

.repair-right {
  position: absolute;
  right: 60px;
  top: 82px;
}

.box-item {
  font-size: 16px !important;
  font-weight: bold !important;
  height: 20px !important;
}

::v-deep .el-card__body {
  padding: 12px 0px 20px 0px;
}

li {
  list-style: none;
}

.btn-repair {
  display: flex;
  margin: 15px;
  justify-content: flex-end;
}

.repair-time-input {
  position: relative;
  width: 80%;
}

@media screen and (max-width: 980px) {
  .repair-right {
    top: 10px;
  }
}

.video-container {
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: center;

  ::v-deep .el-upload-list {
    display: none;
  }
}

.video-warpper {
  position: relative;
  width: 640px;
  height: 360px;
}

.canvas {
  position: absolute;
  left: 0;
  top: 0;
}

.video-footer {
  display: flex;
  height: 50px;
  padding: 10px;
  align-items: center;
}

::v-deep .viewImg .el-upload--picture-card {
  display: none;
}

.btn-replace {
  height: 32px;
  margin-left: 8px;
}

::v-deep .avue-crud__menu {
  display: none;
}

.isReload {
  display: block;
  margin: 6px 0px 0px 30px !important;
}
.repiar_location_class {
  margin: 0 13px 0 78px;
}
.history-record {
  display: flex;
  justify-content: flex-end;
}
.repairWay {
  display: flex;
  flex-direction: column;
  .repairWayContent {
    display: flex;
    padding: 10px;
    .station {
      display: flex;
      flex-direction: row;
    }
    .el-radio:nth-child(1) {
      margin-top: 9px;
    }
    label {
      width: 150px;
      color: #606266;
      span {
        color: red;
      }
    }
  }
}
</style>
